﻿using Microsoft.AspNetCore.Mvc;
using RuoVea.Gantt.Models;
using SqlSugar;
using RuoVea.ExUtil;
using RuoVea.Gantt.Entity;
using RuoVea.Gantt.AuthorizeEx;
using System.Security.Claims;

namespace RuoVea.Gantt.Controllers
{
    [Authorize]
    public class TaskController : Controller
    {
        private readonly ISqlSugarClient _sqlSugarClient;
        public TaskController(ISqlSugarClient sqlSugarClient)
        {
            _sqlSugarClient = sqlSugarClient; ;
        }

        [Route("TaskList")]
        public IActionResult index()
        {
            ViewBag.data = TasksList().Json2Str();
            return View();
        }

        [HttpGet]
        public IActionResult TasksView(string? id)
        {
            long? userId = UserId();
         
            ViewBag.id = id;

            if (id.IsNullOrWhiteSpace()|| userId == null)
            {
                ViewBag.data = new GanttTtasks() { start = DateTime.Now, end = DateTime.Now.AddDays(3) };
            }
            else
            {
                var data = _sqlSugarClient.Queryable<GanttTtasks>().Where(x => x.id ==Int64.Parse( id)).First();
                ViewBag.data = data;
            }

            ViewBag.type = _sqlSugarClient.Queryable<GanttItem>().ToList();
            ViewBag.Start = _sqlSugarClient.Queryable<GanttStart>().ToList();
            ViewBag.Priority = _sqlSugarClient.Queryable<GanttPriority>().ToList();
            return View();
        }

        [HttpPost]
        public IActionResult TasksView(GanttTtasks data)
        {
            long? userId = UserId();
            if (userId == null) return Content((new { code = 0, msg = "未获取到登录凭证." }).Json2Str());
            if (data.label.IsNullOrWhiteSpace())
                return Content((new { code = 0, msg = "名称不能为空." }).Json2Str());
            try
            {
                data.start = new DateTime(data.start.Year, data.start.Month, data.start.Day, 0, 0, 0);
                data.end = new DateTime(data.end.Year, data.end.Month, data.end.Day, 23, 59, 59);
                data.duration = (long)(data.end - data.start).TotalMilliseconds;
                data.IsDeleted = 0;
                data.CreatedUserId= userId; 
                data.CreatedTime= DateTime.Now; 
                if (data.id == 0 || data.id == null)
                {
                    data.id = ExIdGen.IdGenerator.Id;
                    var resInt = _sqlSugarClient.Insertable<GanttTtasks>(data).IgnoreColumns(true).ExecuteCommand();
                    if (resInt > 0)
                        return Content((new { code = 1, msg = "提交处理成功." }).Json2Str());
                }
                else
                {
                    if (data.StartId == 3)
                        data.progress = data.percent = 100;
                    var resInt = _sqlSugarClient.Updateable<GanttTtasks>(data).IgnoreColumns(true).ExecuteCommand();
                    if (resInt > 0)
                        return Content((new { code = 1, msg = "提交处理成功." }).Json2Str());
                }
            }
            catch(Exception ex)
            {
            }
            return Content((new { code = 0, msg = "提交处理失败,请重试." }).Json2Str());
        }

        [NonAction]
        public long? UserId() {
           
            if (User.Identity.IsAuthenticated)
            {
               string subValue = ((ClaimsIdentity)User.Identity).Claims.Where(x=>x.Type=="sub").Select(x=>x.Value).FirstOrDefault();
                if (subValue.IsNullOrWhiteSpace()) 
                    return null;
                return Int64.Parse(subValue); 
            }
            return null;
        }

     [NonAction]
        private List<TasksModel> TasksList()
        {
            long? userId = UserId();
            if (userId == null) return new List<TasksModel>();
            var data = _sqlSugarClient
                    .Queryable<GanttTtasks>()
                    .InnerJoin<GanttItem>((a, b) => a.ItemId == b.Id).Where((a, b) => a.CreatedUserId==userId)
                    .InnerJoin<GanttStart>((a, b, c) => a.StartId == c.Id)
                    .InnerJoin<GanttPriority>((a, b, c, d) => a.PriorityId == d.Id).OrderBy((a, b, c, d) => a.start)
                    .Select((a, b, c, d) => new TasksModel
                    {
                        id = a.id??0,
                        label = a.label,
                        collapsed = a.collapsed,
                        dependentOns = a.dependentOn,
                        end = a.end,
                        start = a.start,
                        parentId = a.parentId,
                        duration = a.duration,
                        percent = a.percent,
                        progress = a.progress,
                        type = b.Code,
                        user = a.user,
                        Color = b.Color,
                        StartName = c.Name,
                        StartColor = c.Color,
                        PriorityName = d.Name,
                        PriorityColor = d.Color,

                    }).ToList();
            return data;
        }
    }
}